package com.mask.token.security.filter;

import com.mask.token.service.MaskTokenService;
import com.mask.token.util.MaskTokenUtil;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * Token认证过滤器
 * 从请求头中提取Token并进行认证
 *
 * @author mask
 * @since 1.0.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MaskTokenAuthenticationFilter extends OncePerRequestFilter {

    private final MaskTokenService tokenService;
    private final UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                   FilterChain filterChain) throws ServletException, IOException {
        
        try {
            String token = MaskTokenUtil.getTokenFromRequest(request);
            
            if (StringUtils.hasText(token) && SecurityContextHolder.getContext().getAuthentication() == null) {
                
                // 验证Token
                if (tokenService.validateToken(token)) {
                    String username = tokenService.getUsernameFromToken(token);
                    
                    if (StringUtils.hasText(username)) {
                        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                        
                        if (userDetails != null) {
                            UsernamePasswordAuthenticationToken authentication = 
                                new UsernamePasswordAuthenticationToken(
                                    userDetails, null, userDetails.getAuthorities());
                            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                            
                            SecurityContextHolder.getContext().setAuthentication(authentication);
                            
                            log.debug("用户 {} 认证成功", username);
                        }
                    }
                } else {
                    log.warn("Token验证失败: {}", token);
                }
            }
        } catch (Exception e) {
            log.error("Token认证过程中发生异常", e);
        }
        
        filterChain.doFilter(request, response);
    }
}
